package lianshi;

/**
 * Created by hasee on 2017/9/25.
 */
public class MyLinkedList {
    class Node {
        Student student;
        Node next = null;
        public Node(Student student) {
            this.student = student;
        }
        public Node() {}

        @Override
        public String toString() {
            return "Node{" +
                    "student=" + student +
                    '}';
        }
    }

    Node head=null;
    int size=0;

    public void add(Student s){//插到列表尾部
        Node node = new Node(s);
        if(size==0){
            head=node;//如果列表为空,把它设为头元素
        }
        else if(size!=0){
            Node temp=head;
            while (temp.next!=null){
                temp=temp.next;
            }
            temp.next=node;
        }
        size++;
    }
    public void add(int index,Student s){//插到指定位置
        Node node = new Node(s);
        Node temp = head;
        if(index == 0){//如果要插到第一个,那么直接换head
            node.next=head;
            head=node;
            size++;
            return;
        }
        for (int i = 0; i <index-1 ; i++) {//从head.next开始找要插入的位置
            temp=temp.next;//循环找到要插入位置的前一个元素
        }
        node.next=temp.next;//把前一个元素的后一个元素设成新插入元素的后一个元素
        temp.next=node;//把要插入位置的前一个元素的后一个元素设成要插入的元素
        size++;
    }

    public Node findByIndex(int index){//通过编号找节点
        Node temp = head;
        if(index==0){
            return temp;
        }
        for (int i = 0; i < index-1; i++) {
            temp=temp.next;
        }
        return temp;
    }

    public MyLinkedList sortByGrade(){
        MyLinkedList myLinkedList = new MyLinkedList();

        Node node = head.next;
        for (int i = 0; i < size; i++) {
            Node max = findByIndex(i);
            for (int j = i+1; j < size; j++) {
                Node temp = findByIndex(j);
                if(temp.student.getGrade()>max.student.getGrade()){
                    max=temp;
                    myLinkedList.add(max.student);
                }
            }
        }
        return myLinkedList;
    }

    public void printAll(){
        Node temp = head;
        for (int i = 0; i <size ; i++) {
            System.out.println(temp);
            temp=temp.next;
        }
    }

    @Override
    public String toString() {
        return "MyLinkedList{" +
                "head=" + head +
                '}';
    }
}
